//
//  ViewController.m
//  LFCWarmSystem
//
//  Created by 李福才 on 16/4/24.
//  Copyright © 2016年 李福才. All rights reserved.
//

#import "ViewController.h"
#import "UIViewController+extension.h"
#import "ModelMainPhone.h"
#import "MyTableViewCell.h"
#import "AddMainPhoneViewController.h"
#import "WarmSystemViewController.h"
#import "PasswordViewController.h"

@interface ViewController ()<AddPhoneDelegate>{
    BOOL isPhoneChangged;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [self dataInit];
    [self addMyTableView];
    [self addMyButton];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
-(void)dataInit{
    _mainPhoneArr = [[DBOperation getDBOperateInstance] selectMainAccountAll];
    if (_mainPhoneArr.count==0) {
        [self setTitle:nil leftBarItemsTitle:nil rightBarItemsTitle:@[NSLocalizedString(@"PassWord_Sample", @"密码")]];
    }else{
        [self setTitle:nil leftBarItemsTitle:@[NSLocalizedString(@"Endit_Sample",@"编辑")] rightBarItemsTitle:@[NSLocalizedString(@"PassWord_Sample", @"密码")]];
    }

}

-(void)addMyTableView{
    _myTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-2*TABLEVIEWCELLHEIGHT)];
    _myTable.tableFooterView = [[UIView alloc] init];
    _myTable.rowHeight = TABLEVIEWCELLHEIGHT;
    _myTable.backgroundColor = BACKGROUNDVIEWCOLOR;
    _myTable.separatorColor = GRAYCOLOR;
    _myTable.delegate = self;
    _myTable.dataSource = self;
    [_myTable setAllowsSelectionDuringEditing:YES];
    [self.view addSubview:_myTable];
}
-(void)addMyButton{
    UIButton *btnAddMainPhone = [UIButton buttonWithType:UIButtonTypeCustom];
    btnAddMainPhone.frame = CGRectMake(50*WIDTHSCALE, _myTable.frame.origin.y+_myTable.frame.size.height+30*WIDTHSCALE, MAINSCREENBOUNDS.size.width -2*50*WIDTHSCALE, TEXTHEIGHT+10);
    [btnAddMainPhone addTarget:self action:@selector(addMainPhone) forControlEvents:UIControlEventTouchUpInside];
    [btnAddMainPhone setTitle:NSLocalizedString(@"AddMainAccount_sample",@"添加主机账户") forState:UIControlStateNormal];
    [btnAddMainPhone setBackgroundImage:[UIImage imageNamed:@"button_large_1b.png"] forState:UIControlStateHighlighted];
    [btnAddMainPhone setBackgroundImage:[UIImage imageNamed:@"button_large_1a.png"] forState:UIControlStateNormal];
    
    [self.view addSubview:btnAddMainPhone];
}
#pragma mark- UITableViewDataSource UITableViewDelegate

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 2.0*TABLEVIEWCELLHEIGHT;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, TABLEVIEWCELLHEIGHT*2.0)];
    UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, TABLEVIEWCELLHEIGHT*3/2.0)];
    lbl.text = NSLocalizedString(@"MainAccount_sample",@"主机账户");
    lbl.textColor = COLOR_MAINHEAD;
    lbl.font = TABLEHEADFONT;
    lbl.textAlignment = NSTextAlignmentCenter;
    [headView addSubview:lbl];
    if (0 < _mainPhoneArr.count) {
//        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, lbl.frame.origin.y+lbl.frame.size.height-1, headView.frame.size.width, 0.5)];
//        lineView.backgroundColor = TEXTCOLOR;
//        [headView addSubview:lineView];
    }
    return headView;
    
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _mainPhoneArr.count;
}

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"MainPhoneCell";
    MyTableViewCell *cell = (MyTableViewCell*)[tableView  dequeueReusableCellWithIdentifier:CellIdentifier];
    if(cell == nil){
        cell = [[MyTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.selectedBackgroundView = [[UIView alloc] initWithFrame:cell.frame];
        cell.selectedBackgroundView.backgroundColor = COLOR_CELLSELECTED_LIGHTBLUE;
    }
    if (0 == indexPath.row) {
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 0.5)];
        lineView.backgroundColor = TEXTCOLOR;
        [cell addSubview:lineView];

    }
    ModelMainPhone *modelPhone = (ModelMainPhone *)[_mainPhoneArr objectAtIndex:indexPath.row];
    NSString *mainPhoneName = (modelPhone.phoneName?modelPhone.phoneName:modelPhone.phoneNumber);
    cell.lblCenter.text = mainPhoneName;
    cell.lblCenter.highlightedTextColor = BLUECOLOR;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(tableView.editing){
        AddMainPhoneViewController *addMainPhoneVC = [[AddMainPhoneViewController alloc] init];
        addMainPhoneVC.model = _mainPhoneArr[indexPath.row];
        addMainPhoneVC.delegate = self;
        UIViewController *vc = [[UINavigationController alloc] initWithRootViewController:addMainPhoneVC];
        [self presentViewController:vc animated:YES completion:^{
        }];

    }
    else{
        WarmSystemViewController *warmSystemVC = [[WarmSystemViewController alloc] init];
        warmSystemVC.modelPhone = [_mainPhoneArr objectAtIndex:indexPath.row];
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        [self.navigationController pushViewController:warmSystemVC animated:YES];
    }
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete;
}
// Moving/reordering

// Allows the reorder accessory view to optionally be shown for a particular row. By default, the reorder control will be shown only if the datasource implements -tableView:moveRowAtIndexPath:toIndexPath:
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
//        [_myTable deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationFade];
        [[DBOperation getDBOperateInstance] deleteMainAccountWithModel:[_mainPhoneArr objectAtIndex:indexPath.row]];
        [_mainPhoneArr removeObjectAtIndex:indexPath.row];
        if (_mainPhoneArr.count==0) {
            [self setTitle:nil leftBarItemsTitle:nil rightBarItemsTitle:@[NSLocalizedString(@"PassWord_Sample", @"密码")]];
        }
        isPhoneChangged = YES;
        [_myTable reloadData];
    }
}
-(void)backAction:(id)sender{
//    编辑
    if (_myTable.isEditing) {
        [_myTable setEditing:NO animated:YES];
        [self setLeftBarItemsTitle:@[NSLocalizedString(@"Endit_Sample",@"编辑")]];
    }else{
        [_myTable setEditing:YES animated:YES];
        [self setLeftBarItemsTitle:@[NSLocalizedString(@"Complete_Sample",@"完成")]];
    }
}
-(void)rightAction:(id)sender{
    PasswordViewController *passwordVC = [[PasswordViewController alloc] init];
    [self.navigationController pushViewController:passwordVC animated:YES];
}

#pragma mark-Button Click
-(void)addMainPhone{
    AddMainPhoneViewController *addMainPhoneVC = [[AddMainPhoneViewController alloc] init];
    addMainPhoneVC.delegate = self;
    UIViewController *vc = [[UINavigationController alloc] initWithRootViewController:addMainPhoneVC];
    [self presentViewController:vc animated:YES completion:^{
    }];
}
-(void)addMainPhoneSuccssed{
    [self dataInit];
    [_myTable reloadData];
}





-(void)viewDidLayoutSubviews{
    if ([_myTable respondsToSelector:@selector(setSeparatorInset:)]) {
        [_myTable setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    
    if ([_myTable respondsToSelector:@selector(setLayoutMargins:)]) {
        [_myTable setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}
@end
